package it.traveldream.entities;

import it.traveldream.dto.ExcursionDTO;
import it.traveldream.dto.HotelDTO.HotelRoomType;
import it.traveldream.dto.TPDTO;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * Entity implementation class for Entity: TravelPackage
 *
 */
@Entity
@Table(name="TravelPackage")

@NamedQuery(
		name = "getAllTPInLocation",
		query = "SELECT tp FROM TravelPackage tp WHERE tp.mean.location = :location"
		)
public class TravelPackage implements Serializable {

	@Id
	@GeneratedValue
	private Long packageId;
	
	private String name;
	
	private static final long serialVersionUID = 1L;
	public Long getPackageId() {
		return this.packageId;
	}
	
	@ManyToOne(optional = false)
	@JoinColumn(name = "MEANID", referencedColumnName = "PRODUCTID", nullable = false)
	private TransportMean mean;
	
	@ManyToOne(optional = false)
	@JoinColumn(name = "HOTELID", referencedColumnName = "PRODUCTID", nullable = false)
	private Hotel hotel;
	
	@ManyToMany
	@JoinTable(
			name="PackagesExcursions",
			joinColumns = @JoinColumn(name = "PACKAGEID", referencedColumnName = "PACKAGEID"),
			inverseJoinColumns = @JoinColumn(name = "EXCURSIONID", referencedColumnName = "PRODUCTID")
	)
	private List<Excursion> excursions = new ArrayList<>();
			
	public TravelPackage() {
		super();
	}

	public TransportMean getMean() {
		return this.mean;
	}

	public void setMean(TransportMean mean) {
		this.mean = mean;
	}

	public Hotel getHotel() {
		return this.hotel;
	}

	public void setHotel(Hotel hotel) {
		this.hotel = hotel;
	}

	public List<Excursion> getExcursions() {
		return this.excursions;
	}

	public void setExcursions(List<Excursion> excursions) {
		this.excursions = new ArrayList<Excursion>(excursions);
	}

	public TPDTO toDTO() {
		TPDTO dto = new TPDTO();
		
		dto.setTPId(this.packageId);
		dto.setName(this.name);
		dto.setMean(this.mean.toDTO());
		dto.setHotel(this.hotel.toDTO());
		
		List<ExcursionDTO> exs = new ArrayList<>();
		for (Excursion e : this.excursions)
			exs.add(e.toDTO());
		dto.setExcursions(exs);

		BigDecimal price = new BigDecimal(Double.MAX_VALUE);
		for (Map.Entry<HotelRoomType, HotelRoom> r : this.hotel.getHotelRooms().entrySet()){
			price = price.min(r.getValue().getPrice());
		}
		price = price.add(this.mean.getPrice());
		for (Excursion e : this.excursions)
			price = price.add(e.getPrice());
		dto.setStartingPrice(price);
		
		return dto;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}
   
}
